<template>
  <div>
    <canvas id="myCanvas" width="400" height="400" >您的浏览器不支持Canvas</canvas>
    <canvas id="myCanvastwo" width="150" height="150" >您的浏览器不支持Canvas</canvas>
    <img :src="imgUrl" class="img">
    <img :src="pic" class="img">
    <div ref="imgBox">
      <h1>今天天气晴</h1>
      <img :src="imgUrl" class="img">
    </div>
  </div>
</template>

<script>
import mimg from '../assets/girl.jpg'
export default {
  name: 'Table',
  data () {
    return {
      imgUrl: '',
      pic: ''
    }
  },
  created () {
  },
  mounted () {
    this.getImg()
    this.huihua()
    this.getpic()
  },
  methods: {
    getImg () {
      var img = new Image()
      img.src = mimg
      var canvas = document.getElementById('myCanvas')
      var context = canvas.getContext('2d')
      img.onload = function () {
        // 绘制水印
        context.font = '14px microsoft yahei'
        context.fillStyle = 'rgba(0, 0, 0, 1)'
        for (var i = 0; i < 4; i++) {
          for (var j = 0; j < 4; j++) {
            context.drawImage(img, 30, 0, 160, 160, j * 100, i * 100, 100, 100)
            context.fillText('my girl', j * 100 + 50, i * 100 + 10)
          }
        }
      }
    },
    huihua () {
      var canvas = document.getElementById('myCanvastwo')
      var ctx = canvas.getContext('2d')
      ctx.fillRect(0, 0, 150, 150)
      ctx.save()

      ctx.fillStyle = '#09F'
      ctx.fillRect(15, 15, 120, 120)
      ctx.save()

      ctx.fillStyle = '#FFF'
      ctx.globalAlpha = 0.5
      ctx.fillRect(30, 30, 90, 90)

      ctx.restore()
      ctx.fillRect(45, 45, 60, 60)

      ctx.restore()
      ctx.fillRect(60, 60, 30, 30)
      this.imgUrl = canvas.toDataURL('image/jpeg', 0.5)
    },
    getpic () {
      this.$html2canvas(this.$refs.imgBox, {
        scale: 1
        // backgroundColor: 'rgba(250, 250, 250, 1)',
        // width: 230,
        // height: 250
      }).then((canvas) => {
        var ctx = canvas.getContext('2d')
        ctx.font = '14px 黑体'
        ctx.fillStyle = 'rgba(0, 0, 0, 1)'
        ctx.fillText('123', 0, 30)
        this.pic = canvas.toDataURL('image/jpeg', 1)
      })
    }
  }
}
</script>
<style lang="less" scoped>
canvas{
  display: inline-block;
  vertical-align: top;
}
</style>
